import axios from 'axios';
// import {
// 	getToken,
// 	removeToken,
// 	setToken
// } from '@/utils/auth'
import { useUserStoreWithOut } from '/@/store/modules/user';
const userStore = useUserStoreWithOut();
// import store from '@/store'
import { message, Modal } from 'ant-design-vue';
// create an axios instance
const service = axios.create({
  // baseURL: '/api', // url = base url + request url
  // baseURL: 'http://192.168.0.107:8080/yzpf',
  //baseURL: 'http://192.168.2.6:8080/yzpf',
  //baseURL: 'http://192.168.2.8:8080/yzpf',
  //baseURL: 'https://yzpf.91yunzu.com/yzpf',
  baseURL: process.env.VUE_APP_API_BASE_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 35000, // request timeout
});

// 请求拦截器，增加token
service.interceptors.request.use(
  (config) => {
    if (userStore.getToken) {
      config.headers = {
        token: userStore.getToken,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 接受拦截器，拦截登录状态和错误判断
service.interceptors.response.use(
  (response) => {
    const refreshToken = response.headers.Authorization || response.headers.authorization;
    if (refreshToken) {
      userStore.removeToken();
      userStore.setToken(refreshToken);
    }
    const res = response.data;
    if (res.code == 200 || res.code == 600) {
      return response.data;
    } else if (res.code == 100) {
      Modal.error({
        title: '登录已过期',
        content: '很抱歉，登录已过期，请重新登录',
        okText: '重新登录',
        mask: false,
        onOk: () => {
          // store.dispatch('user/logout').then(() => {
          // 	location.reload()
          // })
        },
      });
    } else {
      message.error(res.msg);
      return Promise.reject('error');
    }
  },
  (error) => {
    const errorRes = error.response;
    if (errorRes.data.code == 100) {
      setTimeout(() => {
        Modal.error({
          title: '登录已过期',
          content: '很抱歉，登录已过期，请重新登录',
          okText: '重新登录',
          mask: false,
          onOk: () => {
            // store.dispatch('user/logout').then(() => {
            // 	location.reload()
            // })
          },
        });
      }, 100);
    } else {
      message.error(errorRes.data.msg || errorRes.data.message || '网络错误');
      return Promise.reject(error);
    }
  },
);
export default service;
